﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using NetDisk.Models;

namespace NetDisk.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class DownloadsController : ControllerBase
    {
        private readonly ApplicationDbContext _dbContext;

        public DownloadsController(ApplicationDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        [HttpGet("{id}")]
        public FileResult Get(int id)
        {
            var file = _dbContext.UploadFiles
                .Where(f => f.Id == id && f.IsDir == false)
                .AsNoTracking()
                .FirstOrDefault();

            var uploadDir = Startup.UploadPath;
            var filename = Path.Combine(uploadDir, file.FileName);
            var stream = System.IO.File.OpenRead(filename);

            return File(stream, "application/octet-stream", file.RealName);
        }
    }
}